package com.yesep.learn.hik.controller;

import com.yesep.learn.hik.sdk.SDKUtils;
import com.yesep.learn.hik.ws.WebSocketServer;

import lombok.extern.slf4j.Slf4j;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Slf4j
@Controller
public class CommonController {

	@RequestMapping("/streamedian")
	public String streamedian() {
		return "streamedian";
	}

	@RequestMapping("/wsh5")
	public String wsh5() {
		return "wsh5";
	}

	@RequestMapping("/online")
	public ModelAndView online(ModelAndView model) {
		log.debug("WebSocketServer.handleMap.size() = " + WebSocketServer.handleOnlineMap.size());
		model.addObject("devices", WebSocketServer.handleOnlineMap);
		model.setViewName("online");
		return model;
	}

	/**
	 * 视频下载
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/downloadVideo")
	public ResponseEntity downloadVideo(HttpServletRequest request) {
		String videoPath = request.getParameter("video");
		System.out.println("videoPath = " + videoPath);
		String filePath = SDKUtils.getVideoPath() + videoPath;
		return export(new File(filePath));
	}

	/**
	 * 图片下载
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/downloadImg")
	public ResponseEntity<FileSystemResource> downloadImg(HttpServletRequest request) {
		String imgPath = request.getParameter("img");
		//文件路径
		String filePath = SDKUtils.getImgPath() + imgPath;
		return export(new File(filePath));
	}

	/**
	 * 文件下载
	 *
	 * @param file
	 * @return
	 */
	public ResponseEntity<FileSystemResource> export(File file) {
		if (file == null) {
			return null;
		}
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Disposition", "attachment;filename=" + file.getName());
		return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(file));
	}

}
